/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.chanjet.donkey.rest;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springside.modules.web.MediaTypes;

import com.chanjet.donkey.entity.Attach;
import com.chanjet.donkey.repository.AttachDao;
import com.chanjet.donkey.util.Constants;

/**
 * Task的Restful API的Controller.
 * 
 * @author calvin
 */
@RestController
@RequestMapping(value = "/api/v1/upload")
public class UploadController {
	@Autowired
	private AttachDao attachDao;
	
	@RequestMapping(method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
	@ResponseBody
	public Result upload(MultipartHttpServletRequest request, HttpServletResponse response) {
		Iterator<String> itr = request.getFileNames();
        
        List<Attach> attachs = new ArrayList<Attach>();
        while (itr.hasNext()) {
        	MultipartFile mpf = request.getFile(itr.next());
            
            String newFilenameBase = UUID.randomUUID().toString();
            String originalFileExtension = mpf.getOriginalFilename().substring(mpf.getOriginalFilename().lastIndexOf("."));
            String newFilename = newFilenameBase + originalFileExtension;
            
            Attach attach = new Attach();
            attach.setName(mpf.getOriginalFilename());
            attach.setSaveName(newFilename);
            attach.setSize(mpf.getSize());
            attach.setExtension(originalFileExtension.replaceFirst("\\.", ""));
            attach.setUploadIp(request.getRemoteHost());
            attach.setType(mpf.getContentType());
            try {
            	String hash = DigestUtils.md5Hex(mpf.getBytes());
            	attach.setHash(hash);
            	mpf.transferTo(new File(Constants.UPLOAD_PATH + newFilename));
            } catch (IOException e) {
            	e.printStackTrace();
            	throw new RestException("upload failed");
            }
            attachs.add(attach);
        }
        attachDao.save(attachs);
		return Result.ok(attachs);
	}
}
